//
//  202. 快乐数.swift
//  LeetCodeTrain
//
//  Created by rjb on 2021/7/12.
//  Copyright © 2021 rjb. All rights reserved.
//

import Foundation
class Solution202  {
    // 这个set 因为不知道具体的个数。所以不能优化
    func isHappy(_ n: Int) -> Bool {
        var dict: [Int:Int] = [:]
        var sum = n
        while true {
            sum = getSum(sum)
            if dict[sum] != nil {
                return false
            }
            dict[sum] = sum
            if sum == 1 {
                return true
            }
        }
    }
    func getSum(_ sum: Int) -> Int {
        var newSum = 0
        var tmp = sum
        while tmp > 0 {
            let num = tmp % 10;
            newSum += num * num
            tmp = tmp / 10
        }
        return newSum
    }
    static func test() {
        let solu = Solution202()
        let flag = solu.isHappy(2)
        print(flag)
    }
}
